<template>
  <div v-if="isLogin" class="chat-assistant"
       :class="{ 'minimized': isMinimized, 'fullscreen': isFullscreen, 'exit-fullscreen': isExitingFullscreen }">
    <div class="chat-header" @click="toggleMinimize">
      <span>聊天助手</span>
      <div class="header-icons">
        <!-- 根据当前状态显示不同的图标 -->
        <i v-if="!isMinimized && !isFullscreen" class="el-icon-full-screen" @click.stop="enterFullscreen"></i>
        <i v-if="isFullscreen" class="el-icon-crop" @click.stop="exitFullscreen"></i>
        <i :class="isMinimized ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
      </div>
    </div>
    <div class="chat-body" v-show="!isMinimized">
      <div class="chat-messages" ref="chatMessages">
        <div v-for="(message, index) in messages" :key="index"
             :class="['message', message.type === 'user' ? 'user-message' : 'assistant-message']">
          <div class="message-content">{{ message.content }}</div>
        </div>
      </div>
      <div class="chat-input">
        <div class="quick-actions" v-if="!isMinimized">
          <el-button size="mini" type="text" @click="askQuestion('课程内容')">课程内容</el-button>
          <el-button size="mini" type="text" @click="askQuestion('作业辅导')">作业辅导</el-button>
          <el-button size="mini" type="text" @click="askQuestion('学习资源')">学习资源</el-button>
          <el-button size="mini" type="text" @click="askQuestion('考试辅导')">考试辅导</el-button>
        </div>
        <el-input
          v-model="inputMessage"
          placeholder="请输入消息..."
          @keyup.enter.native="sendMessage"
        >
          <el-button slot="append" icon="el-icon-s-promotion" @click="sendMessage"></el-button>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script>
import {EventSourcePolyfill} from 'event-source-polyfill'
import {getToken} from "@/utils/auth";

export default {
  name: "ChatAssistant",
  data() {
    return {
      isLogin: !!getToken(),
      sseSource: null,
      isMinimized: true,
      isFullscreen: false,
      isExitingFullscreen: false,
      inputMessage: "",
      messages: [
        {
          type: "assistant",
          content: "您好！我是雅橙学习助手，有什么可以帮助您的吗？"
        }
      ]
    };
  },
  watch: {
    '$store.state.user.token'(newVal) {
      this.isLogin = !!newVal;
    }
  },
  methods: {
    // 切换最小化状态
    toggleMinimize() {
      // 如果当前是全屏状态，先退出全屏到展开状态
      if (this.isFullscreen) {
        this.exitFullscreen();
        return;
      }

      // 否则在最小化和展开之间切换
      this.isMinimized = !this.isMinimized;
    },

    // 进入全屏状态（只能从展开状态进入）
    enterFullscreen() {
      if (!this.isMinimized && !this.isFullscreen) {
        this.isFullscreen = true;
      }
    },

    // 退出全屏状态（回到展开状态）
    exitFullscreen() {
      if (this.isFullscreen) {
        this.isExitingFullscreen = true;
        setTimeout(() => {
          this.isFullscreen = false;
          this.isExitingFullscreen = false;
        }, 300); // 动画持续时间
      }
    },

    // 其他方法保持不变
    sendMessage() {
      if (!this.inputMessage.trim()) return;

      // 添加用户消息
      this.messages.push({
        type: "user",
        content: this.inputMessage
      });

      const userMessage = this.inputMessage;
      this.inputMessage = "";

      // 模拟助手回复
      setTimeout(() => {
        this.messages.push({
          type: "assistant",
          content: ""
        });
        this.getAssistantResponse(userMessage)
        // 滚动到底部
        this.$nextTick(() => {
          if (this.$refs.chatMessages) {
            this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
          }
        });
      }, 500);
    },
    askQuestion(type) {
      let question = "";
      switch (type) {
        case "课程内容":
          question = "请介绍一下当前课程的主要内容";
          break;
        case "作业辅导":
          question = "我在作业中遇到了困难，能提供一些指导吗？";
          break;
        case "学习资源":
          question = "有哪些推荐的学习资源？";
          break;
        case "考试辅导":
          question = "如何准备即将到来的考试？";
          break;
        default:
          question = "您好，我需要帮助";
      }

      this.inputMessage = question;
      this.sendMessage();
    },
    getAssistantResponse(message) {
      // 扩展现有的回复逻辑，添加教学相关的回复
      // 关闭已有连接
      if (this.sseSource) {
        this.sseSource.close();
      }
      // 创建新连接
      this.sseSource = new EventSourcePolyfill(process.env.VUE_APP_BASE_API + "/ai/chat/stream?message=" + message, {headers: {'Authorization': `Bearer ${getToken()}`}});
      // 监听进度消息
      this.sseSource.addEventListener('chat', (event) => {
        // 获取最后一条消息
        const lastMessage = this.messages[this.messages.length - 1];
        if (lastMessage && lastMessage.type === 'assistant') {
          // 1. 判断是否需要添加空格
          const needSpace = lastMessage.content && event.data &&
            /[a-zA-Z]$/.test(lastMessage.content) && // 检查上一段文本是否以英文字母结尾
            /^[a-zA-Z]/.test(event.data);           // 检查新文本是否以英文字母开头

          // 2. 根据判断结果拼接文本
          lastMessage.content += (needSpace ? ' ' : '') + event.data;
        } else {
          this.messages.push({
            type: 'assistant',
            content: event.data
          });
        }
        // 滚动到底部
        this.$nextTick(() => {
          if (this.$refs.chatMessages) {
            this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
          }
        });
      });
      // 监听连接关闭
      this.sseSource.addEventListener('done', () => {
        this.sseSource.close();
        this.sseSource = null;
      });

      // 监听错误
      this.sseSource.onerror = (error) => {
        console.error('SSE连接错误:', error);
        this.sseSource.close();
        this.sseSource = null;
      };
    }
  },
  mounted() {
    // 初始化时滚动到底部
    this.$nextTick(() => {
      if (this.$refs.chatMessages) {
        this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
      }
    });
  }
};
</script>

<style scoped>
.chat-assistant {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 350px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  transform-origin: bottom right;
}

.chat-assistant.fullscreen {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  border-radius: 0;
  animation: expandFromRight 0.3s ease-out;
}

.chat-assistant.exit-fullscreen {
  animation: shrinkToRight 0.3s ease-in;
}

@keyframes expandFromRight {
  0% {
    transform: scale(0.3);
    opacity: 0.7;
    right: 20px;
    bottom: 20px;
    top: auto;
    left: auto;
    width: 350px;
    height: 400px;
  }
  100% {
    transform: scale(1);
    opacity: 1;
    right: 0;
    bottom: 0;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}

@keyframes shrinkToRight {
  0% {
    transform: scale(1);
    opacity: 1;
    right: 0;
    bottom: 0;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  100% {
    transform: scale(0.3);
    opacity: 0.7;
    right: 20px;
    bottom: 20px;
    top: auto;
    left: auto;
    width: 350px;
    height: 400px;
  }
}

.chat-assistant.fullscreen .chat-body {
  height: calc(100% - 40px);
}

.chat-assistant.minimized {
  width: 200px;
  height: auto;
}

.chat-header {
  padding: 10px 15px;
  background-color: #409EFF;
  color: white;
  border-radius: 8px 8px 0 0;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-assistant.fullscreen .chat-header {
  border-radius: 0;
}

.header-icons {
  display: flex;
  align-items: center;
}

.header-icons i {
  margin-left: 10px;
  cursor: pointer;
}

.chat-body {
  display: flex;
  flex-direction: column;
  height: 400px;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
}

.user-message {
  align-items: flex-end;
}

.assistant-message {
  align-items: flex-start;
}

.message-content {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 6px;
  word-break: break-word;
}

.user-message .message-content {
  background-color: #409EFF;
  color: white;
}

.assistant-message .message-content {
  background-color: #e5e5e5;
  color: #333;
}

.chat-input {
  padding: 10px;
  border-top: 1px solid #eee;
}

.quick-actions {
  display: flex;
  justify-content: space-around;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.quick-actions .el-button {
  margin: 0 2px;
  font-size: 12px;
}
</style>
